package com.sheng.leetcode.year2022.month03.day07;

import org.junit.Test;

/**
 * @Date 2022/3/7 11:23
 * @author liusheng
 * 504. 七进制数
 * 给定一个整数 num，将其转化为 7 进制，并以字符串形式输出。
 *
 * 示例 1:
 *
 * 输入: num = 100
 * 输出: "202"
 * 示例 2:
 *
 * 输入: num = -7
 * 输出: "-10"
 *
 * 提示：
 *
 * -107 <= num <= 107
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/base-7
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LeetCode0504 {

    @Test
    public void test01(){
        int num = 100;
        System.out.println(Integer.toString(num, 7));
        System.out.println(new Solution().convertToBase7(num));
    }

}
class Solution {
    int ints = 7;
    public String convertToBase7(int num) {
        StringBuilder stringBuilder = null;
        if (num < 0) {
            num = Math.abs(num);
            stringBuilder = new StringBuilder("-");
            StringBuilder stringBuilder1 = new StringBuilder("");
            while (num / ints != 0) {
                stringBuilder1.append(num % ints);
                num /= ints;
            }
            stringBuilder1.append(num % ints);
            stringBuilder.append(stringBuilder1.reverse());
        } else {
            stringBuilder = new StringBuilder("");
            while (num / ints != 0) {
                stringBuilder.append(num % ints);
                num /= ints;
            }
            stringBuilder.append(num % ints);
            stringBuilder.reverse();
        }
        return stringBuilder.toString();
    }
}
//class Solution {
//    public String convertToBase7(int num) {
//        if (num == 0) {
//            return "0";
//        }
//        boolean negative = num < 0;
//        num = Math.abs(num);
//        StringBuffer digits = new StringBuffer();
//        while (num > 0) {
//            digits.append(num % 7);
//            num /= 7;
//        }
//        if (negative) {
//            digits.append('-');
//        }
//        return digits.reverse().toString();
//    }
//}
